package cn.iune.web.security.shiro;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import com.alibaba.fastjson.JSONObject;

import cn.iune.common.response.ResultData;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
--------------------- 
作者：Michael_Zhan_Tcys 
来源：CSDN 
原文：https://blog.csdn.net/u012138272/article/details/79840275 
版权声明：本文为博主原创文章，转载请附上博文链接！
*/

//shiro登录认证检查过滤器（自定义）
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
	
	/**
	   * 在访问controller前判断是否登录，返回json，不进行重定向。
     * @param request
     * @param response
     * @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String uri = httpServletRequest.getRequestURI();
        
        String projectName = httpServletRequest.getServletContext().getContextPath();
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    	System.out.println("shiro.MyFormAuthenticationFilter.onAccessDenied-->>"+uri);
        //判断是否为ajax
        if (isAjax(request)) {
        	System.out.println("MyFormAuthenticationFilter.onAccessDenied-->>ajax请求-->>"+uri);
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            ResultData resultData = new ResultData();
            resultData.setCode(-999);
            resultData.setMsg("登录认证失效，请重新登录!");
            httpServletResponse.getWriter().write(JSONObject.toJSON(resultData).toString());
        } else {
        	System.out.println("MyFormAuthenticationFilter.onAccessDenied-->>非ajax请求-->>"+uri);
            //saveRequestAndRedirectToLogin(request, response);
            /**
             * @Mark 非ajax请求重定向为登录页面
             */
            httpServletResponse.sendRedirect(projectName + this.getLoginUrl());
        }
        return false;
    }

    private boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
    
    /*
	--------------------- 
	作者：Michael_Zhan_Tcys 
	来源：CSDN 
	原文：https://blog.csdn.net/u012138272/article/details/79840275 
	版权声明：本文为博主原创文章，转载请附上博文链接！
    */

}
